package com.geniusk.system.service.impl;

import com.geniusk.system.model.mapper.RoleMapper;
import com.geniusk.system.model.mapper.UserRoleMapper;
import com.geniusk.system.model.pojo.UserRole;
import com.geniusk.system.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public int insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        if (roleIds != null && roleIds.length > 0) {
            //判断角色是否存在
            boolean isExist = roleMapper.selectRoleIsExistByRoleIds(roleIds);
            if (isExist) {
                // 新增用户与角色管理
                List<UserRole> list = new ArrayList<>();
                for (Long roleId : roleIds) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(userId);
                    userRole.setRoleId(roleId);
                    list.add(userRole);
                }
                return userRoleMapper.insertUserRole(list);
            }
        }
        return 0;
    }
}
